$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'joblog/pageList',
        mtype: "POST",
        datatype: "json",
        colModel: [
			{ label: '任务ID', name: 'id', index: 'id', width: 50, key: true },
			{ label: '调度时间', name: 'triggerTime', index: 'triggerTime', width: 80 },
            { label: '调度结果', name: 'triggerCode', sortable: false, width: 75, formatter: function(value, options, row){
                    if (value == 200) {
                        value = '<span style="color: green">成功</span>';
                    } else if (value == 500) {
                        value = '<span style="color: red">失败</span>';
                    } else if (value == 0) {
                        value = '';
                    }
                    return value;
                }},
			{ label: '调度备注', name: 'triggerMsg', search:false, width: 80, formatter: function(value, options, row){
                    return value?'<a class="logTips" onclick="vm.showMsg(this)" href="javascript:;" >查看<span style="display:none;">'+ value +'</span></a>':'无';
            }},
			{ label: '执行时间', name: 'handleTime', sortable: false, width: 80},
			{ label: '执行结果', name: 'handleCode', sortable: false, width: 80, formatter: function(value, options, row){
                    if (value == 200) {
                        value = '<span style="color: green">成功</span>';
                    } else if (value == 500) {
                        value = '<span style="color: red">失败</span>';
                    } else if (value == 502) {
                        value = '<span style="color: red">失败（超时）</span>';
                    } else if (value == 0) {
                        value = '';
                    }
                    return value;
            }},
			{ label: '执行备注', name: 'handleMsg', sortable: false, width: 80,formatter: function(value, options, row){
                    return value?'<a class="logTips" onclick="vm.showMsg(this)" href="javascript:;" >查看<span style="display:none;">'+ value +'</span></a>':'无';
                }},
			{ label: '操作', name: 'handleMsg', width: 80,sortable: false,search: false, formatter: function(value, options, row){
                    if (row.triggerCode == 200 || row.handleCode != 0){
                        var logKillDiv = '';
                        if(row.handleCode == 0){
                            logKillDiv = '&nbsp;&nbsp;<a href="javascript:void(0);" onclick="vm.killJob(\''+row.id+'\')" class="btn btn-danger btn-label">&nbsp;终止任务</a>';

                        }

                        var html = '<a href="javascript:void(0);" onclick="vm.executeLog(\''+row.id+'\')" class="btn btn-info btn-label">&nbsp;执行日志</a>' + logKillDiv;

                        return html;
                    }
                    return "";
            }},
        ],
		viewrecords: true,
        height: 'auto',
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        //width: document.body.clientWidth,根据body的宽度使用这个请注释掉autowidth:true
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "data.data",
            page: "data.pageNum",
            total: "data.pages",
            records: "data.recordCounts"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
    $("#jqGrid").filterToolbar({}).jqGrid('navGrid',"#jqGridPager",{//刷新按钮
        refresh: true,
        edit:false,del: false,search:false,add:false
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
        JobInfoList: [],
        autoRegister: true,
		title: null,
        q:{
            jobGroup: -1,
            logStatus: -1,
            jobId: -1
        }
	},
	methods: {
		query: function () {
			vm.reload();
		},
        killJob: function(logId, callback){
            layer.confirm( ('确定终止任务?'), {
                icon: 3,
                title: '系统提示' ,
                btn: [ '确定', '取消' ]
            }, function(index){
                layer.close(index);
                $.ajax({
                    type : 'POST',
                    url : 'joblog/logKill',
                    data : {"id":logId},
                    dataType : "json",
                    success : function(r){
                        if (r.code == 200) {
                            layer.alert('操作成功');
                            if(callback){
                                callback();
                            }
                            vm.reload();
                        } else {
                            layer.alert(r.msg);
                        }
                    },
                });
            });
        },
        executeLog: function(logId){
            $.ajax({
                type: "GET",
                url: baseURL + "joblog/logInfo?id="+logId,
                success: function(r){
                    if(r.code == 0){
                        if(r.data.triggerCode == 200 && r.data.handleCode == 0){
                            vm.showDetail(r.data.id, true);
                        }else{
                            vm.showDetail(r.data.id, false);
                        }
                    }else{
                        layer.alert(r.msg);
                    }
                }
            });
        },
        changeJobGroup: function(){
		    vm.q.jobId = -1;
            $.ajax({
                type : 'POST',
                async: false,   // async, avoid js invoke pagelist before jobId data init
                url : baseURL + 'joblog/getJobsByGroup',
                data : {"jobGroup": vm.q.jobGroup},
                dataType : "json",
                success : function(data){
                    if (data.code == 200) {
                        vm.JobInfoList = data.content;
                        vm.query();
                    } else {
                        layer.alert(data.msg);
                    }
                },
            });
        },
        showDetail: function(logId, isRun){
            var index = layer.open({
                type: 2,
                id: "showDetail",
                scrollbar: false,
                title: false,
                area: ['100%', '100%'],
                shadeClose: false,
                closeBtn: false,
                shade:0.7,
                skin: 'myskin',
                content: baseURL + 'joblog/logDetailPage?id=' + logId,
                success: function(layero, index){
                    var child = document.getElementById("layui-layer-iframe"+index).contentWindow;
                    // 初始化传递layer下标，用于iframe控制父窗口组件
                    child.initLayer(index);
                },
                btn: ['暂停刷新', '终止任务', '关闭']
                ,yes: function(index, layero){
                    var child = document.getElementById("layui-layer-iframe"+index).contentWindow;
                    var btn = $("#layui-layer"+index).find(".layui-layer-btn").find(".layui-layer-btn0");
                    if(btn.html() == "暂停刷新"){
                        child.logRunStop("暂停刷新...");
                        $("#layui-layer"+index).find(".layui-layer-btn").find(".layui-layer-btn0").html("继续刷新");
                    }else{
                        child.logRunFn();
                        $("#layui-layer"+index).find(".layui-layer-btn").find(".layui-layer-btn0").html("暂停刷新");
                    }
                },btn2: function(index, layero){
                    vm.killJob(logId, function(){
                        $("#layui-layer"+index).find(".layui-layer-btn").find(".layui-layer-btn1").hide();
                    });
                    return false;
                }
            });
            if(!isRun){
                $("body").find(".layui-layer-btn").find(".layui-layer-btn0").hide();
                $("body").find(".layui-layer-btn").find(".layui-layer-btn1").hide();
            }
        },
		showMsg: function(obj){
            var msg = $(obj).find('span').html();
            layer.open({
                type: 1,
                title: false,
                area: ['50%', '95%'],
                shadeClose: false,
                shade:0.7,
                skin: 'myskin',
                content: msg
            });
		},
		delShow: function (event) {
            var jobGroup = $("#queryJobGroup").val();
            var jobId = $("#queryJobInfo").val();

            var jobGroupText = $("#queryJobGroup").find("option:selected").text();
            var jobIdText = $("#queryJobInfo").find("option:selected").text();

            $('#clearLogModal input[name=jobGroup]').val(jobGroup);
            $('#clearLogModal input[name=jobId]').val(jobId);

            $('#clearLogModal .jobGroupText').val(jobGroupText);
            $('#clearLogModal .jobIdText').val(jobIdText);

            $('#clearLogModal').modal('show');
		},
        del: function(){
            $.post(baseURL + "joblog/clearLog",  $("#clearLogModal .form").serialize(), function(data, status) {
                if (data.code == "200") {
                    $('#clearLogModal').modal('hide');
                    vm.query();
                } else {
                    layer.alert(data.msg);
                }
            });
        },
		getInfo: function(id){
			$.get(baseURL + "jobgroup/loadById?id="+id, function(r){
			    if(r.code == 200){
                    vm.jobgroup = r.content;
                }else{
			        alert(r.msg);
                }
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{
                    'logStatus': vm.q.logStatus,
                    'jobGroup': vm.q.jobGroup,
                    'jobId': vm.q.jobId,
                },
                page:page
            }).trigger("reloadGrid");
		}
	}
});